<template>
  <div class="profile-view">
    <a-page-header title="个人中心" />
    <a-card class="profile-card">
      <a-tabs v-model:activeKey="activeTab">
        <a-tab-pane key="1" tab="账户信息">
          <a-form
            :model="userForm"
            :rules="rules"
            ref="formRef"
            layout="vertical"
          >
            <a-form-item label="用户名" name="username">
              <a-input
                v-model:value="userForm.username"
                placeholder="请输入用户名"
              />
            </a-form-item>
            <a-form-item label="手机号码" name="phone">
              <a-input
                v-model:value="userForm.phone"
                placeholder="请输入手机号码"
              />
            </a-form-item>
            <a-form-item label="收货地址" name="address">
              <a-textarea
                v-model:value="userForm.address"
                rows="3"
                placeholder="请输入收货地址"
              />
            </a-form-item>
            <a-form-item>
              <a-button
                type="primary"
                :loading="loading"
                @click="handleUpdateUser"
              >保存修改</a-button
              >
              <a-button style="margin-left: 10px" @click="handleResetForm"
              >重置</a-button
              >
            </a-form-item>
          </a-form>
          <a-divider />
          <a-button type="link" @click="showPasswordModal">修改密码</a-button>
        </a-tab-pane>
      </a-tabs>
    </a-card>

    <!-- 修改密码模态框 -->
    <a-modal
      v-model:open="passwordModalVisible"
      title="修改密码"
      @ok="handleUpdatePassword"
      @cancel="passwordModalVisible = false"
      :confirmLoading="passwordLoading"
    >
      <a-form
        :model="passwordForm"
        :rules="passwordRules"
        ref="passwordFormRef"
        layout="vertical"
      >
        <a-form-item label="旧密码" name="oldPassword">
          <a-input-password
            v-model:value="passwordForm.oldPassword"
            placeholder="请输入旧密码"
          />
        </a-form-item>
        <a-form-item label="新密码" name="newPassword">
          <a-input-password
            v-model:value="passwordForm.newPassword"
            placeholder="请输入新密码"
          />
        </a-form-item>
        <a-form-item label="确认密码" name="confirmPassword">
          <a-input-password
            v-model:value="passwordForm.confirmPassword"
            placeholder="请再次输入新密码"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { message } from "ant-design-vue";
import { updateUser } from "@/api/userController";
import {useLoginUserStore} from "@/stores/user.ts";

// 标签页当前激活key
const activeTab = ref("1");

// 加载状态
const loading = ref(false);
const passwordLoading = ref(false);

// 表单refs
const formRef = ref();
const passwordFormRef = ref();

// 用户表单数据
const userForm = reactive({
  id: "",
  username: "",
  phone: "",
  address: "",
});

// 表单校验规则
const rules = {
  username: [{ required: true, message: "请输入用户名", trigger: "blur" }],
  phone: [
    { required: true, message: "请输入手机号码", trigger: "blur" },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入正确的手机号码格式",
      trigger: "blur",
    },
  ],
  address: [{ required: true, message: "请输入收货地址", trigger: "blur" }],
};

// 密码修改相关
const passwordModalVisible = ref(false);
const passwordForm = reactive({
  oldPassword: "",
  newPassword: "",
  confirmPassword: "",
});

// 密码修改表单校验规则
const passwordRules = {
  oldPassword: [{ required: true, message: "请输入旧密码", trigger: "blur" }],
  newPassword: [
    { required: true, message: "请输入新密码", trigger: "blur" },
    { min: 6, message: "密码长度不能少于6位", trigger: "blur" },
  ],
  confirmPassword: [
    { required: true, message: "请确认新密码", trigger: "blur" },
    {
      validator: (rule: any, value: string) => {
        if (value !== passwordForm.newPassword) {
          return Promise.reject("两次输入的密码不一致");
        }
        return Promise.resolve();
      },
      trigger: "blur",
    },
  ],
};
const loginUser = useLoginUserStore();
// 获取用户信息
const fetchUserInfo = async () => {
      userForm.id = loginUser.loginUser.id;
      userForm.username = loginUser.loginUser.userName;
      userForm.phone = loginUser.loginUser?.phone || '15398651261';
      userForm.address = loginUser.loginUser?.address || '湖南省长沙理工大学';
};

// 更新用户信息
const handleUpdateUser = async () => {
  try {
    await formRef.value.validate();
    loading.value = true;
    const res = await updateUser({
      id: userForm.id,
      username: userForm.username,
      phone: userForm.phone,
      address: userForm.address,
    });

    if (res.data.code === 0 && res.data.data) {
      await loginUser.fetchLoginUser()
      message.success("保存成功");

    } else {
      message.error(res.data.message || "保存失败");
    }
  } catch (error) {
    console.error("更新用户信息出错:", error);
    message.error("表单验证失败或保存失败");
  } finally {
    loading.value = false;
  }
};

// 重置表单
const handleResetForm = () => {
  formRef.value.resetFields();
  fetchUserInfo(); // 重新获取用户信息
};

// 显示修改密码模态框
const showPasswordModal = () => {
  passwordModalVisible.value = true;
  // 重置密码表单
  if (passwordFormRef.value) {
    passwordFormRef.value.resetFields();
  }
};

// 修改密码
const handleUpdatePassword = async () => {
  try {
    await passwordFormRef.value.validate();
    passwordLoading.value = true;

    // 这里需要调用修改密码API，假设已经实现了updatePassword函数
    // const res = await updatePassword({
    //   id: userForm.id,
    //   oldPassword: passwordForm.oldPassword,
    //   newPassword: passwordForm.newPassword
    // });

    // 模拟API调用成功
    setTimeout(() => {
      message.success("密码修改成功，请重新登录");
      passwordModalVisible.value = false;
      passwordLoading.value = false;

      // 清空密码表单
      passwordForm.oldPassword = "";
      passwordForm.newPassword = "";
      passwordForm.confirmPassword = "";

      // 可能需要跳转到登录页或执行登出操作
      // router.push('/login');
    }, 1000);
  } catch (error) {
    console.error("修改密码出错:", error);
    message.error("表单验证失败或修改密码失败");
    passwordLoading.value = false;
  }
};

// 组件挂载时获取用户信息
onMounted(() => {
  fetchUserInfo();
});
</script>

<style scoped>
.profile-view {
  padding: 24px;
  width: 100%;
  max-width: 100%;
  margin: 0;
  background-color: #f5f7fa;
  min-height: calc(100vh - 64px);
}

.profile-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

:deep(.ant-tabs-nav) {
  margin-bottom: 24px;
}

:deep(.ant-form-item) {
  margin-bottom: 24px;
}

:deep(.ant-input) {
  border-radius: 4px;
}

:deep(.ant-btn-primary) {
  height: 40px;
  border-radius: 4px;
  font-weight: 500;
}

:deep(.ant-divider) {
  margin: 24px 0;
}
</style>
